package com.cetc32.dh.utils;

import org.apache.logging.log4j.util.Base64Util;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class FileUtil {

    /**
     * 在basePath下保存上传的文件夹
     *
     * @param basePath
     * @param files
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files) {

        if (files == null || files.length == 0) {
            if (files == null) {
                System.out.println("files为空！！");
                return;
            }
            System.out.println("files长度为0");
            return;
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            String filePath = basePath + "/" + file.getOriginalFilename();
            System.out.println(filePath);
            makeDir(filePath);
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 确保目录存在，不存在则创建
     *
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }


    /**
     * 目录文件上传
     *
     * @param files
     * @param filepath
     */
    public static String uploadFile(MultipartFile[] files, String filepath) {
        System.out.println(files.length);
        if (files.length == 0) {
            return null;
        }
        int uploadsSum = 0;
        String FileDir = null;
        for (int i = 0; i < files.length; i++) {
            String flag = "";
            MultipartFile file = files[i];
            String fileName = file.getOriginalFilename();//获取文件名
            String dirName = filepath +File.separator + fileName;
            FileDir = fileName;
            System.out.println(FileDir);
            System.out.println(dirName);
            makeDir(dirName);

            if (true) {        //!file.isEmpty()
                try (BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(dirName)))) {
                    out.write(file.getBytes());
                    out.flush();
                    flag = "文件上传成功";
                } catch (FileNotFoundException e) {
                    flag = "文件上传失败";
                } catch (IOException e) {
                    flag = "文件上传失败";
                }
            }
            if (flag.equals("文件上传成功")) {
                uploadsSum++;
            }
        }
        if (uploadsSum == files.length) {
            if (FileDir.contains("/")){
                return FileDir.substring(0,FileDir.indexOf("/"));
            }
            return FileDir;

        }
        return FileDir+"上传失败";
    }

    /**
     * 文件下载
     *
     * @param response
     * @param filename
     * @param path
     */
    public static void downloadFile(HttpServletResponse response, String filename, String path){
        if (filename != null) {
            FileInputStream is = null;
            BufferedInputStream bs = null;
            OutputStream os = null;
            try {
                File file = new File(path);
                if (file.exists()) {
                    //设置Headers
                    response.setHeader("Content-Type","application/octet-stream");
                    //设置下载的文件的名称-该方式已解决中文乱码问题
                    response.setHeader("Content-Disposition","attachment;filename=" +  new String( filename.getBytes("gb2312"), "ISO8859-1" ));
                    is = new FileInputStream(file);
                    bs =new BufferedInputStream(is);
                    os = response.getOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len = bs.read(buffer)) != -1){
                        os.write(buffer,0,len);
                    }
                }else{
                    String error = Base64Util.encode("下载的文件资源不存在");
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }finally {
                try{
                    if(is != null){
                        is.close();
                    }
                    if( bs != null ){
                        bs.close();
                    }
                    if( os != null){
                        os.flush();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 判断是否为目录
     * @param file
     * @return boolean
     */
    public static boolean isDirectory(String file) {
        File f = new File(file);
        return f.isDirectory();
    }

    /**
     * 拷贝目录文件到新路径
     * @param oldPath
     * @param newPath
     * @return boolean
     */
    public static boolean copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                    System.out.println("#################################");
                    System.out.println(temp);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                    System.out.println("#################################");
                    System.out.println(temp);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
            System.out.println("复制整个文件夹内容操作成功");
            return true;
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
            return false;

        }
    }

    /**
     * 删除目录
     * @param dirPath
     */
    public static void deleteDir(String dirPath)
    {
        File file = new File(dirPath);
        if(file.isFile())
        {
            file.delete();
        }else
        {
            File[] files = file.listFiles();
            if(files == null)
            {
                file.delete();
            }else
            {
                for (int i = 0; i < files.length; i++)
                {
                    deleteDir(files[i].getAbsolutePath());
                }
                file.delete();
            }
        }
    }

    /**
     * 将文件内容写到新的文件中
     * @param fileName
     * @param savepath
     * @return String
     */
    public static String writeFile(String fileName, String savepath) {
        System.out.println(fileName);
//        File readerfile = new File(fileName);
        String readerfile = fileName;
        String outFile = savepath +  File.separator +fileName.split("/")[fileName.split("/").length-1];
        makeDir(outFile);
//        File writerfile = new File(outFile);
        String writerfile =outFile;

        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 将读取文件对象加载进字符读取对象中
            fileInputStream = new FileInputStream(readerfile);
            // 将字符读取对象加载进字符读取缓冲流对象
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            // 将写入的文件对象加载进字符写入对象中
            fileOutputStream = new FileOutputStream(writerfile);
            // 将字符写入对象加载进字符写入缓冲流对象中
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            // 按行获取读取缓冲流中的数据
            int bytes=-1;

            while ((bytes = bufferedInputStream.read())!=-1) {
                bufferedOutputStream.write(bytes);
            }
            return (fileName.split("/")[fileName.split("/").length-1]+"下载成功！");
        } catch (IOException e) {
            e.printStackTrace();
            return fileName.split("/")[fileName.split("/").length-1]+"下载失败！";
        } finally {
            // 关闭文件流对象
            try {
                if (bufferedInputStream != null)
                    bufferedInputStream.close();
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();
                if (fileOutputStream != null)
                    fileOutputStream.close();
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e2) {
                e2.printStackTrace();
                return fileName.split("/")[fileName.split("/").length-1]+"下载失败！";
            }
        }

    }


    /**
     * 文件名后缀前添加一个时间戳
     */
    public static String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        String nowTimeStr; // 当前时间
        Date date = new Date();
        SimpleDateFormat sif = new SimpleDateFormat("yyyyMMddHHmmss");
        nowTimeStr = sif.format(date);

//      fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);

        fileName=fileName+"_"+nowTimeStr;

        return fileName;
    }


    /**
     * 获取目录中所有的文件名
     * @param  directoryPath
     */
    public static List<String> getAllFile(String directoryPath) {
        List<String> list = new ArrayList<String>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                list.addAll(getAllFile(file.getAbsolutePath()));
            } else {
                list.add(file.getAbsolutePath());
            }
        }

        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
        System.out.println("###############################!!!!!!!!!");
        return list;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }


}

